//
//  WhereamiAppDelegate.m
//  Whereami
//
//  Created by Xia Yong on 12-12-20.
//  Copyright (c) 2012年 Xia Yong. All rights reserved.
//

#import "WhereamiAppDelegate.h"
#import "MapPoint.h"

@interface WhereamiAppDelegate() <CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate>

// 当CLLocationManager对象定位到用户位置时发送此消息。
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation;

// 当CLLocationManager对象定位失败时发送此消息。
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;

// 当MKMapView对象定位到用户位置发生改变时发送此消息
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation;

// 当UITextField将要接收用户输入时UITextField对象将向它的委托对象发送此消息。
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;

// 当用户按下键盘的回车键时UITextField对象将向它的委托对象发送此消息。
- (BOOL)textFieldShouldReturn:(UITextField *)textField;

- (void) findLocation;

- (void) foundLocation:(CLLocation *) location;

@end

@implementation WhereamiAppDelegate

@synthesize window = _window;
@synthesize locationManager = _locationManager;
@synthesize worldView = _worldView;
@synthesize locationTitleField = _locationTitleField;
@synthesize activityIndicator = _activityIndicator;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 创建CLLocationManager对象。
    self.locationManager = [[CLLocationManager alloc] init];
    
    // 设置CLLocationManager对象的委托对象为当前对象。
    // 当前对象遵守了CLLocationManagerDelegate协议。
    [self.locationManager setDelegate:self];
    
    // 设置MKMapView对象的委托对象为当前对象。
    // 当前对象遵循了MKMapViewDelegate协议。
    [self.worldView setDelegate:self];
    
    // 设置UITextField对象的委托对象为当前对象。
    // 当前对象遵循了UITextFieldDelegate协议。
    [self.locationTitleField setDelegate:self];
    
    // 要求CLLocationManager对象返回所有结果。
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    
    // 不考虑话费时间和电力
    // 要求CLLocationManager对象返回的结果尽可能准确。
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    // 要求CLLocationManager对象开始工作，定位设备位置。
    //[self.locationManager startUpdatingLocation];
    
    // 让MKMapView对象显示用户当前位置。
    [self.worldView setShowsUserLocation:YES];
    
    [[self window] makeKeyAndVisible];
    return YES;
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation {
    NSLog(@"%@", newLocation);
    
    // 获取该心位置是多少秒前创建的。
    NSTimeInterval timeInterval = [[newLocation timestamp] timeIntervalSinceNow];
    
    // CLLocationManager对象可能会返回设备最近一次定位到的位置
    // 不应该使用缓存数据，如果位置信息是在3分钟前得到的就将其忽略。
    if (timeInterval < -180) {
        return;
    }
    
    [self foundLocation:newLocation];
}

- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSString *errorMessage = [NSString stringWithFormat:@"Could not find location: %@", error];
    NSLog(@"%@", errorMessage);
}

- (void) mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    CLLocationCoordinate2D loc = [userLocation coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
    [mapView setRegion:region animated:YES];
}

- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    textField.text = @"";
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self findLocation];
    
    // 放弃第一响应对象状态，键盘消失。
    [textField resignFirstResponder];
    
    return YES;
}

- (void) findLocation {
    // 让CLLocationManager对象开始定位。
    [self.locationManager startUpdatingLocation];
    
    // 开启活动指示器的动画。
    [self.activityIndicator startAnimating];
    
    // 隐藏UITextField对象。
    self.locationTitleField.hidden = YES;
}

- (void) foundLocation:(CLLocation *)location {
    CLLocationCoordinate2D coordinate = [location coordinate];
    
    // 创建MapPoint实例。
    MapPoint *mapPoint = [[MapPoint alloc] initWithCoordinate:coordinate title:self.locationTitleField.text];
    
    // 将mapPoint加入到worldView中。
    [self.worldView addAnnotation:mapPoint];
    
    [mapPoint release];
    
    // 放大地区区域至一下位置。
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate, 1000, 1000);
    [self.worldView setRegion:region animated:YES];
    
    //self.locationTitleField.text = @"";
    
    // 停止活动指示器的动画。
    [self.activityIndicator stopAnimating];
    
    // 让CLLocationManager对象停止定位。
    [self.locationManager stopUpdatingLocation];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

- (void)dealloc {
    [_worldView release];
    [_locationTitleField release];
    [_activityIndicator release];
    [super dealloc];
}
@end
